import streamlit as st
import re
# # 设置 Mapbox Token
# data = {
#     'latitude': [37.7749, 34.0522, 40.7128],
#     'longitude': [-122.4194, -118.2437, -74.0060],
#     'name': ['San Francisco', 'Los Angeles', 'New York']
# }
#
# st.map(data, zoom=4, use_container_width=True)
import streamlit as st
import pandas as pd
import numpy as np
import pydeck as pdk
from pydeck.bindings.base_map_provider import BaseMapProvider
from streamlit.hello.utils import show_code

# 设置 Mapbox 令牌
mapbox_token = "pk.eyJ1IjoiOTIxMTE3IiwiYSI6ImNtM2VhbmhmczBjYzIycnB6NDE0eWU3eTQifQ.gs7Gkexm6P-d7BNuLkLf9w"


def mapping_draw():
    # 将 Mapbox 令牌传递给 Streamlit
    st.pydeck_chart(pdk.Deck(
        map_style='mapbox://styles/mapbox/light-v10',
        initial_view_state=pdk.ViewState(
            latitude=37.76,
            longitude=-122.4,
            zoom=11,
            pitch=50,
        ),
        layers=[
            pdk.Layer(
                'HexagonLayer',
                data=pd.DataFrame(
                    np.random.randn(1000, 2) / [50, 50] + [37.76, -122.4],
                    columns=['lat', 'lon']),
                get_position='[lon, lat]',
                radius=200,
                elevation_scale=4,
                elevation_range=[0, 1000],
                pickable=True,
                extruded=True,
            ),
        ],
        api_keys={'mapbox': mapbox_token},
        map_provider=BaseMapProvider.MAPBOX.value
    ))


def mapping_showPath():
    # 示例车机运动轨迹数据
    trajectory_data = pd.DataFrame({
        'lat': [37.76, 37.75, 37.74, 37.73, 37.72],
        'lon': [-122.4, -122.41, -122.42, -122.43, -122.44],
        'name': ['Point 1', 'Point 2', 'Point 3', 'Point 4', 'Point 5']
    })

    # 创建一个轨迹图层
    trajectory_layer = pdk.Layer(
        'LineLayer',
        data=trajectory_data,
        get_source_position='[lon, lat]',
        get_target_position=['lon', 'lat'],
        get_color=[255, 0, 0, 160],
        get_width=5
    )

    # 创建一个标记图层
    marker_layer = pdk.Layer(
        'ScatterplotLayer',
        data=trajectory_data,
        get_position='[lon, lat]',
        get_color=[0, 0, 255, 160],
        get_radius=100,
        pickable=True,
    )

    # 设置视图状态
    view_state = pdk.ViewState(
        latitude=37.75,
        longitude=-122.42,
        zoom=12,
        pitch=50,
    )

    # 创建 Deck 对象
    r = pdk.Deck(
        layers=[trajectory_layer, marker_layer],
        initial_view_state=view_state,
        # mapbox://styles/mapbox/satellite-streets-v12
        map_style='mapbox://styles/mapbox/satellite-streets-v12',
        api_keys={'mapbox': mapbox_token},
        tooltip={"text": "{name}"}
    )

    # 在 Streamlit 中显示地图
    st.pydeck_chart(r)


mapping_draw()
# show_code(mapping_draw)


# mapping_showPath()
st.write("Map with Mapbox token integrated.")


show_code(mapping_showPath)


st.download_button(
    label="下载 CSV 文件",
    data='新方案.md',
    file_name='新方案.md',
    mime='text/csv',
)

# 读取 Markdown 文件
with open("新方案.md", "r", encoding="utf-8") as file:
    markdown_text = file.read()


# 在 Streamlit 应用中显示 Markdown 内容，同时处理图片
def render_markdown_with_images(markdown_text):
    # 匹配 Markdown 图片语法 ![alt text](image_url)
    pattern = re.compile(r'!\[.*?\]\((.*?)\)')

    # 记录上一个位置
    last_pos = 0

    # 查找所有匹配项
    for match in pattern.finditer(markdown_text):
        # 显示上一个位置到匹配位置之间的文本
        st.markdown(markdown_text[last_pos:match.start()], unsafe_allow_html=True)

        # 显示图片
        img_url = match.group(1)
        print(img_url)
        st.image(img_url)

        # 更新上一个位置
        last_pos = match.end()

    # 显示剩余的文本
    st.markdown(markdown_text[last_pos:], unsafe_allow_html=True)


# 调用函数显示内容
render_markdown_with_images(markdown_text)

# Mermaid 序列图内容
sequence_diagramsequence_diagram ="""mermaid
sequenceDiagram
    participant Alice
    participant Bob
    Alice->>John: Hello John, how are you?
    loop Healthcheck
        John->>John: Fight against hypochondria
    end
    Note right of John: Rational thoughts <br/>prevail...
    John-->>Alice: Great!
    John->>Bob: How about you?
    Bob-->>John: Jolly good!
"""

"-------------"
# Mermaid 序列图内容
sequence_diagram = """mermaid
sequenceDiagram
    participant Alice
    participant Bob
    Alice->>John: Hello John, how are you?
    loop Healthcheck
        John->>John: Fight against hypochondria
    end
    Note right of John: Rational thoughts <br/>prevail...
    John-->>Alice: Great!
    John->>Bob: How about you?
    Bob-->>John: Jolly good!
"""

# 自定义 HTML 和 JavaScript 用于显示 Mermaid 图
# 自定义 HTML 和 JavaScript 用于显示 Mermaid 图
mermaid_html = f"""
<!DOCTYPE html>
<html>
<head>
    <script type="module">
        import mermaid from 'https://cdn.jsdelivr.net/npm/mermaid@10/dist/mermaid.esm.min.mjs';
        mermaid.initialize({{ startOnLoad: true }});
    </script>
</head>
<body>
    <div class="mermaid">
        {sequence_diagram}
    </div>
</body>
</html>
"""

# 使用 st.markdown 显示 Mermaid 图
st.markdown(mermaid_html, unsafe_allow_html=True)

#st.markdown(sequence_diagramsequence_diagram, unsafe_allow_html=True)